package com.infodms.dms.actions.conservation;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.repairOrder.RoMaintainMain;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.Utility;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.conservation.EnergyConservationDlrDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TtVsEnergyConservationChgPO;
import com.infodms.dms.po.TtVsEnergyConservationPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.StringUtil;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

public class EnergyConservationDlr {
	
	private EnergyConservationDlrDao dao = EnergyConservationDlrDao.getInstance();
	private Logger logger = Logger.getLogger(RoMaintainMain.class);
	private final String ENERGY_CON_APPLY_QUERY = "/jsp/conservation/conDlr/benefitPeople_Init.jsp";// 申请查询页面
	private final String ENERGY_CON_DETAIL_QUERY = "/jsp/conservation/conDlr/benefitPeople_qry.jsp";// 申请查询页面
	private final String ENERGY_CON_DETAIL = "/jsp/conservation/conDlr/benefitPeople_Dlr_Dtl.jsp";// 申请查询页面
	private final String ENERGY_CON_REPORT = "/jsp/conservation/conDlr/benefitPeople_report.jsp";// 申请页面
	private final String dtl_URL = "/jsp/conservation/conDlr/jnhm_qry_dtl.jsp";// 申请查询明细页面
	private final String ENERGY_CON_VIEW_DETAIL = "/jsp/conservation/conDlr/benefitPeople_Dlr_Dtl.jsp";// 申请页面
	/**
	 * 
	 * @Title: roForward
	 * @Description: TODO(车辆节能惠民信息申请)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void vehicleEnergyConApply() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(
				Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String COMMAND = CommonUtils.checkNull(request.getParamValue("COMMAND"));
			if(!"".equals(COMMAND)){
				String dealerId = logonUser.getDealerId();
				Long poseId = logonUser.getPoseId();
				String saleStartDate = CommonUtils.checkNull(request.getParamValue("saleStartDate"));
				String saleEndDate = CommonUtils.checkNull(request.getParamValue("saleEndDate"));
				String model = CommonUtils.checkNull(request.getParamValue("model"));
				String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
				String vin = CommonUtils.checkNull(request.getParamValue("vin"));
				if (null != vin && !"".equals(vin)) {
					vin = vin.trim();
				}
				Integer curPage = request.getParamValue("curPage") != null ? Integer
						.parseInt(request.getParamValue("curPage"))
						: 1; // 处理当前页
				PageResult<Map<String,Object>> ps = dao.saleVehicleQuery(
						saleStartDate,saleEndDate,model,areaId,vin,
						dealerId, curPage, Constant.PAGE_SIZE);
				act.setOutData("ps", ps);
			}else{
				List<Map<String, Object>> areaBusList=MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
				act.setOutData("areaBusList", areaBusList);
				act.setForword(ENERGY_CON_APPLY_QUERY);
			}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "车辆节能惠民信息申请");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	/**
	 * 节能惠民提报（DLR）
	 */
	public void vehicleEnergyConReport() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(
				Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String COMMAND = CommonUtils.checkNull(request.getParamValue("COMMAND"));
			if(!"".equals(COMMAND)){
				String invoceNo = "NO"+CommonUtils.checkNull(request.getParamValue("invoceNo"));
				String modelId = CommonUtils.checkNull(request.getParamValue("modelId"));
				String orgId = CommonUtils.checkNull(request.getParamValue("orgId"));
				
				
				String vin = CommonUtils.checkNull(request.getParamValue("vin"));
				String purChasedDate = CommonUtils.checkNull(request.getParamValue("purChasedDate"));
				String modelCode = CommonUtils.checkNull(request.getParamValue("modelName"));
				String modelName = CommonUtils.checkNull(request.getParamValue("modelCode"));
				String vichId = CommonUtils.checkNull(request.getParamValue("vichId"));
				String vichNo = CommonUtils.checkNull(request.getParamValue("vichNo"));
				
				String factoryPrice = CommonUtils.checkNull(request.getParamValue("factoryPrice"));
				String salePrice = CommonUtils.checkNull(request.getParamValue("salePrice"));
				String dealerName = CommonUtils.checkNull(request.getParamValue("dealerName"));
				String dealerCode = logonUser.getDealerCode();
				String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
				String dPro = CommonUtils.checkNull(request.getParamValue("dPro"));
				String dCity = CommonUtils.checkNull(request.getParamValue("dCity"));
				String saleZipCode1 = CommonUtils.checkNull(request.getParamValue("saleZipCode1"));
				String linkPerson1 = CommonUtils.checkNull(request.getParamValue("linkPerson1"));
				String linkTel1 = CommonUtils.checkNull(request.getParamValue("linkTel1"));
				String saleZipCode2 = CommonUtils.checkNull(request.getParamValue("saleZipCode2"));
				String salesId = CommonUtils.checkNull(request.getParamValue("salesId"));
				String address2 = CommonUtils.checkNull(request.getParamValue("address2"));
				String ctmId = CommonUtils.checkNull(request.getParamValue("ctmId"));
				String cPro = CommonUtils.checkNull(request.getParamValue("cPro"));
				String cCity = CommonUtils.checkNull(request.getParamValue("cCity"));
				String cTown = CommonUtils.checkNull(request.getParamValue("cTown"));
				String ctmName = CommonUtils.checkNull(request.getParamValue("ctmName"));
				String linkPerson2 = CommonUtils.checkNull(request.getParamValue("linkPerson2"));
				String linkTel2 = CommonUtils.checkNull(request.getParamValue("linkTel2"));
				String remark = CommonUtils.checkNull(request.getParamValue("remark"));
				TtVsEnergyConservationPO energy = new TtVsEnergyConservationPO();
				energy.setConservationId(Utility.getLong(SequenceManager.getSequence("")));
				//生成申请编号
//				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
//				Calendar   calendar = Calendar.getInstance();
//				String timeStr = sdf2.format(calendar.getTime()).toString();
				String jNo = Utility.GetBillNo("",dealerCode,"JNO");
//				String jNo = Utility.getString(SequenceManager.getSequence("JNO"));
				jNo = jNo.substring(jNo.length()-11);
				jNo = "JN"+dealerCode+jNo;
				//转换日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				
				
				energy.setConservationNo(jNo);
				energy.setConservationStatus(Constant.VEHICLE_ENERGY_CON_APPLY);
				energy.setCtmAddress(address2);
				energy.setCtmId(Long.valueOf(ctmId));
				energy.setCtmLinkman(linkPerson2);
				energy.setCtmLinktel(linkTel2);
				energy.setCtmProviceId(Long.valueOf(cPro));
				energy.setCtmCityId(Long.valueOf(cCity));
				energy.setCtmTownId(Long.valueOf(cTown));
				energy.setCtmZipCode(Integer.parseInt(saleZipCode2));
				energy.setDealerId(Long.valueOf(dealerId));
				energy.setDlrAddress(address2);
				energy.setDlrLinkman(linkPerson1);
				energy.setDlrProviceId(Long.valueOf(dPro));
				energy.setDlrCityId(Long.valueOf(dCity));
				energy.setDlrLinktel(linkTel1);
				energy.setDlrZipCode(Integer.valueOf(saleZipCode1));
				energy.setExportFlag(0l);
				energy.setExportPose(0l);
				energy.setExportUser(0l);
				energy.setFactoryPrice(Double.valueOf(factoryPrice));
				energy.setInvoceNo(invoceNo);
				energy.setIsExport(0);
				energy.setModelId(Long.valueOf(modelId));
				energy.setOrgId(Long.valueOf(orgId));
				energy.setRemark(remark);
				energy.setSalesDate(sdf.parse(purChasedDate));
				energy.setSalesId(Long.valueOf(salesId));
				energy.setSalesPrice(Double.parseDouble(salePrice));
				energy.setStatus(Constant.STATUS_ENABLE);
				energy.setUpdateBy(logonUser.getUserId());
				energy.setUpdateDate(new Date());
				energy.setCreateBy(logonUser.getUserId());
				energy.setCreateDate(new Date());
				energy.setVehicleId(Long.valueOf(vichId));
				energy.setVehicleNo(vichNo);
				dao.insert(energy);
				
				//记录申请审核状态
				TtVsEnergyConservationChgPO chg = new TtVsEnergyConservationChgPO();
				chg.setChangeId(Utility.getLong(SequenceManager.getSequence("")));
				chg.setConservationId(energy.getConservationId());
				chg.setCreateBy(logonUser.getUserId());
				chg.setCreateDate(new Date());
				chg.setDescription("");
				chg.setStatus(Constant.VEHICLE_ENERGY_CON_APPLY);
				dao.insert(chg);
				act.setOutData("jNo", jNo);
			}else{
				String vehicleId = CommonUtils.checkNull(request.getParamValue("vehicleId"));
				Map<String, Object> map = dao.saleVehicleDetailQuery(vehicleId);
				act.setOutData("map", map);
				act.setForword(ENERGY_CON_REPORT);
			}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "节能惠民提报");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	/**
	 * 节能惠民信息查询（DLR）
	 */
	public void vehicleEnergyConQuery() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(
				Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String COMMAND = CommonUtils.checkNull(request.getParamValue("COMMAND"));
			if(!"".equals(COMMAND)){
				String dealerId = logonUser.getDealerId();
//				String saleStartDate = CommonUtils.checkNull(request.getParamValue("saleStartDate"));
//				String saleEndDate = CommonUtils.checkNull(request.getParamValue("saleEndDate"));
				String reportStartDate = CommonUtils.checkNull(request.getParamValue("reportStartDate"));
				String reportEndDate = CommonUtils.checkNull(request.getParamValue("reportEndDate"));
//				String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode"));
				String model = CommonUtils.checkNull(request.getParamValue("model"));
//				String orgId = CommonUtils.checkNull(request.getParamValue("orgId"));
				String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
				String energyNo = CommonUtils.checkNull(request.getParamValue("energyNo"));
				String vin = CommonUtils.checkNull(request.getParamValue("vin"));
				if (null != vin && !"".equals(vin)) {
					vin = vin.trim();
				}
//				String dPro = CommonUtils.checkNull(request.getParamValue("dPro"));
//				String dCity = CommonUtils.checkNull(request.getParamValue("dCity"));
				String status = CommonUtils.checkNull(request.getParamValue("status"));
				
				Integer curPage = request.getParamValue("curPage") != null ? Integer
						.parseInt(request.getParamValue("curPage"))
						: 1; // 处理当前页
				
				PageResult<Map<String,Object>> ps = dao.energyConViewQuery(
						reportStartDate, reportEndDate, model, 
						 areaId, status, energyNo, vin, dealerId,
						curPage, Constant.PAGE_SIZE);
				act.setOutData("ps", ps);
			}else{
				List<Map<String, Object>> areaBusList=MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
				act.setOutData("areaBusList", areaBusList);
				act.setForword(ENERGY_CON_DETAIL_QUERY);
			}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "节能惠民信息查询");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	/**
	 * 节能惠民信息查看（DLR）
	 */
	public void vehicleEnergyConView() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(
				Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String COMMAND = CommonUtils.checkNull(request.getParamValue("COMMAND"));
			if(!"".equals(COMMAND)){
				String dealerId = logonUser.getDealerId();
				String reportStartDate = CommonUtils.checkNull(request.getParamValue("reportStartDate"));
				String reportEndDate = CommonUtils.checkNull(request.getParamValue("reportEndDate"));
				String model = CommonUtils.checkNull(request.getParamValue("model"));
				String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
				String energyNo = CommonUtils.checkNull(request.getParamValue("energyNo"));
				String vin = CommonUtils.checkNull(request.getParamValue("vin"));
				String status = CommonUtils.checkNull(request.getParamValue("status"));
				
				Integer curPage = request.getParamValue("curPage") != null ? Integer
						.parseInt(request.getParamValue("curPage"))
						: 1; // 处理当前页
				
				PageResult<Map<String,Object>> ps = dao.energyConViewQuery(
						reportStartDate, reportEndDate, model, 
						 areaId, status, energyNo, vin, dealerId,
						curPage, Constant.PAGE_SIZE);
				act.setOutData("ps", ps);
			}else{
				String conservationId = CommonUtils.checkNull(request.getParamValue("conservationId"));
				
				Map<String, Object> map = dao.energyConDetailCheck(conservationId);
				List<Map<String, Object>> listEnergyConStatus = dao.energyConStatusInfo(conservationId);
				act.setOutData("map", map);
				act.setOutData("listEnergyConStatus", listEnergyConStatus);
				act.setOutData("conservationId",conservationId );
				act.setForword(ENERGY_CON_VIEW_DETAIL);
			}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "节能惠民信息查看");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 车辆节能惠民主页面主查询
	 */
	public void mainQuery(){
		 ActionContext act = ActionContext.getContext();
		 RequestWrapper req = act.getRequest() ;
		 AclUserBean user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			
			String beginDate = req.getParamValue("beginDate");//上报开始时间
			String endDate = req.getParamValue("endDate");//上报结束时间			
			String areaId = req.getParamValue("areaId");//业务范围
			String materialCode = req.getParamValue("materialCode");//车型
			String status = req.getParamValue("status");//状态
			String No = req.getParamValue("No");//节能惠民编号
			String vin = req.getParamValue("vin");//vin	
			
			
			StringBuffer con = new StringBuffer();
			if(StringUtil.notNull(No))
				con.append("  and s.CONSERVATION_NO like '%").append(No).append("%'\n");
			if(StringUtil.notNull(vin))
				con.append("  and TV.VIN = ").append(vin).append("\n");
			
			if(StringUtil.notNull(areaId))
				
				con.append(" AND EXISTS (SELECT H.AREA_ID FROM TM_DEALER_BUSINESS_AREA H WHERE H.DEALER_ID=S.DEALER_ID AND H.AREA_ID LIKE '%"+areaId+"%') \n");
			
			// 选择物料组
			if (null != materialCode && !"".equals(materialCode)) {
				String[] materialCodes = materialCode.split(",");
				if (null != materialCodes && materialCodes.length > 0) {
					StringBuffer buffer = new StringBuffer();
					for (int i = 0; i < materialCodes.length; i++) {
						buffer.append("'").append(materialCodes[i]).append("'")
								.append(",");
					}
					buffer = buffer.deleteCharAt(buffer.length() - 1);
				    con.append("       and  (S.MODEL_ID IN (SELECT G.GROUP_ID \n");
					con.append("                             FROM TM_VHCL_MATERIAL_GROUP G \n");
					con.append("                            WHERE G.GROUP_CODE IN (" + buffer.toString() + "))) \n");
				}
			}
			
			
			if(null != status && !"".equals(status)
					&& !"-1".equals(status))
				con.append("  and s.STATUS = ").append(status).append("\n");

			if(StringUtil.notNull(beginDate))
				con.append("  and s.CREATE_DATE>=to_date('").append(beginDate).append(" 00:00:00','YYYY-MM-DD hh24:mi:ss')\n");
			if(StringUtil.notNull(endDate))
				con.append("  and s.CREATE_DATE<=to_date('").append(endDate).append(" 23:59:59','YYYY-MM-DD hh24:mi:ss')\n");
			
			con.append("  and s.DEALER_ID in (").append(user.getDealerId()).append(")\n");
			
			int pageSize = 10;
			Integer curPage = req.getParamValue("curPage") !=null ? Integer.parseInt(req.getParamValue("curPage")) : 1;
			PageResult<Map<String,Object>> ps = dao.mainQuery(con.toString(), pageSize, curPage);
			act.setOutData("ps",ps);
		} catch(Exception e){
			BizException be = new BizException(act,e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "车辆节能惠民");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*public void vehicledtl() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(
				Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String COMMAND = CommonUtils.checkNull(request.getParamValue("COMMAND"));
				String conservationId = CommonUtils.checkNull(request.getParamValue("conservationId"));
				
				Map<String, Object> map = dao.energyConDetailCheck(conservationId);
				List<Map<String, Object>> listEnergyConStatus = dao.energyConStatusInfo(conservationId);
				act.setOutData("map", map);
				act.setOutData("listEnergyConStatus", listEnergyConStatus);
				act.setOutData("conservationId",conservationId );
				act.setForword(dtl_URL);
		//	}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "车辆节能惠民查询信息");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}*/
	
	
}
